﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using DevCorner.Services.Interfaces;
using System.Collections.Generic;

namespace DevCorner.Services
{
  //[ServiceContract(Namespace = "http://www.alexgolesh.com/schemas")]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class RegistrationService : IRegistrationService
  {
    public static event EventHandler<SubscriptionEventArgs> Subscribed;

    private static List<Uri> subscribers = new List<Uri>();
    private static object obj = new object();

    #region IRegistrationService Members

    public void Register(string uri)
    {
#if DEBUG
      System.Diagnostics.Debug.WriteLine(uri);
#endif

      Uri channelUri = new Uri(uri, UriKind.Absolute);
      Subscribe(channelUri);
    }

    public void Unregister(string uri)
    {
      Uri channelUri = new Uri(uri, UriKind.Absolute);
      Unsubscribe(channelUri);
    }

    public List<Uri> GetRegisteredSubscribers()
    {
      return subscribers;
    }
    #endregion

    #region Helper public funvtionality
    public static List<Uri> GetSubscribers()
    {
      return subscribers;
    }
    #endregion

    #region Subscribtion/Unsubscribtion logic
    private void Subscribe(Uri channelUri)
    {
      lock (obj)
      {
        if (!subscribers.Exists((u) => u == channelUri))
        {
          subscribers.Add(channelUri);
        }
      }
      OnSubscribed(channelUri, true);
    }

    public static void Unsubscribe(Uri channelUri)
    {
      lock (obj)
      {
        subscribers.Remove(channelUri);
      }
      OnSubscribed(channelUri, false);
    }
    #endregion

    #region Helper private functionality
    private static void OnSubscribed(Uri channelUri, bool isActive)
    {
      EventHandler<SubscriptionEventArgs> handler = Subscribed;
      if (handler != null)
      {
        handler(null, new SubscriptionEventArgs(channelUri, isActive));
      }
    }
    #endregion

    #region Internal SubscriptionEventArgs class definition
    public class SubscriptionEventArgs : EventArgs
    {
      public SubscriptionEventArgs(Uri channelUri, bool isActive)
      {
        this.ChannelUri = channelUri;
        this.IsActive = isActive;
      }

      public Uri ChannelUri { get; private set; }
      public bool IsActive { get; private set; }
    }
    #endregion
  }
}
